package com.sc.nft.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.sc.nft.dao.ActivityCouponsUserDao;
import com.sc.nft.dao.IdcardInfoDao;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.ReceiveVerificationDTO;
import com.sc.nft.enums.MallMemberEquityTypeEnum;
import com.sc.nft.enums.MemberEquityTemplateeceiveCycleEnum;
import com.sc.nft.enums.ReceiveStatusEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户领取优惠券记录服务实现
 *
 * @author liGen
 * @version 1.0
 * @date 2023/12/5 4:39 下午
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ActivityCouponsUserServiceImpl implements ActivityCouponsUserService {

    private final ActivityCouponsUserDao activityCouponsUserDao;
    private final UserCouponsService userCouponsService;
    @Autowired
    ActivityCouponsService activityCouponsService;
    private final MallMemberService mallMemberService;
    private final MallMemberEquityService mallMemberEquityService;
    private final MallMemberEquityTargetService mallMemberEquityTargetService;
    private final MallMemberEquityTemplateService mallMemberEquityTemplateService;
    private final IdcardInfoDao idcardInfoDao;

    /**
     * 用户领取优惠券活动
     *
     * @param activityCouponsId 活动优惠券ID
     * @param userInfo          用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void userReceive(Long activityCouponsId, UserInfo userInfo, Long memberId, Long memberEquityTemplateId) {
        ActivityCoupons activityCoupons = activityCouponsService.getById(activityCouponsId);
        // 优惠券领取校验
        MallMemberEquityTemplate mallMemberEquityTemplate = null;
        MallMemberEquity mallMemberEquity = null;
        if (Objects.nonNull(memberId) && Objects.nonNull(memberEquityTemplateId)) {
            mallMemberEquityTemplate = mallMemberEquityTemplateService.getById(memberEquityTemplateId);
            mallMemberEquity = mallMemberEquityService.get(memberEquityTemplateId, memberId);
        }
        ReceiveVerificationDTO receiveVerificationDTO = receiveVerification(activityCoupons.getId(), activityCoupons.getStartTime(), activityCoupons.getEndTime(), userInfo, mallMemberEquity, mallMemberEquityTemplate);
        if (ReceiveStatusEnum.CAN_PICK == receiveVerificationDTO.getReceiveStatusEnum()) {
            // 用户领取优惠券
            UserCoupons userCoupons = userCouponsService.receive(activityCoupons, userInfo);
            // 创建优惠券活动用户领取记录
            create(activityCoupons, userInfo, userCoupons, mallMemberEquity);
        } else {
            throw new GlobalRunTimeException(receiveVerificationDTO.getReceiveStatusEnum().getRemark());
        }
    }

    /**
     * 优惠券领取校验
     *
     * @param activityId 活动优惠券ID
     * @param startTime  活动开始时间
     * @param endTime    活动结束时间
     * @param userInfo
     * @return
     */
    @Override
    public ReceiveVerificationDTO receiveVerification(Long activityId, Date startTime, Date endTime, UserInfo userInfo,
                                                      MallMemberEquity mallMemberEquity, MallMemberEquityTemplate mallMemberEquityTemplate) {
        Date now = new Date();
        ReceiveVerificationDTO receiveVerificationDTO = new ReceiveVerificationDTO();
        if (DateTime.now().after(endTime)) {
            // 活动已结束
            receiveVerificationDTO.setReceiveStatusEnum(ReceiveStatusEnum.ACTIVITY_HAS_ENDED);
            return receiveVerificationDTO;
        }
        if (DateTime.now().before(startTime)) {
            // 活动未开始
            receiveVerificationDTO.setReceiveStatusEnum(ReceiveStatusEnum.ACTIVITY_NOT_STARTED);
            return receiveVerificationDTO;
        }

        // 获取用户该优惠券活动下的有效优惠券
        List<UserCoupons> validUserCoupons = userCouponsService.getValidUserCoupons(userInfo.getId(), activityId);
        if (Objects.nonNull(mallMemberEquity) && Objects.nonNull(mallMemberEquityTemplate)) {
            if (MallMemberEquityTypeEnum.BIRTHDAY_GIFT_BAG == mallMemberEquityTemplate.getType()) {
                // 生日礼
                IdcardInfo idcardInfo = idcardInfoDao.getByUserIdAndIsPass(userInfo.getId());
                if (Objects.isNull(idcardInfo)) {
                    receiveVerificationDTO.setReceiveStatusEnum(ReceiveStatusEnum.RESTRICTED_ACCESS);
                    return receiveVerificationDTO;
                }
                String pattern = "yyyyMMdd";
                // 创建SimpleDateFormat对象，指定日期格式
                SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
                try {
                    // 从身份证号获取出生日期
                    String birthDateStr = idcardInfo.getCardId().substring(10, 14);
                    String year = String.valueOf(DateUtil.thisYear());
                    birthDateStr = year + birthDateStr;
                    // 解析出生日期字符串为日期对象
                    Date birthDate = dateFormat.parse(birthDateStr);
                    Date birthEndTime = DateUtil.endOfDay(birthDate);
                    Date birthStartTime = DateUtil.beginOfDay(DateUtil.offsetDay(birthDate,-15));
                    if (now.after(birthEndTime) || now.before(birthStartTime)) {
                        receiveVerificationDTO.setRemainingNumberOfReceive(0);
                        receiveVerificationDTO.setReceiveStatusEnum(ReceiveStatusEnum.RESTRICTED_ACCESS);
                        return receiveVerificationDTO;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            Date startDate = null;
            Date endDate = null;
            MemberEquityTemplateeceiveCycleEnum receiveCycle = mallMemberEquityTemplate.getReceiveCycle();
            Map<String, Date> timeMap = receiveCycle.getTimeMap(now);
            if (Objects.nonNull(timeMap)) {
                startDate = timeMap.get("startTime");
                endDate = timeMap.get("endTime");
            }
            // 限制领取 获取已经领取的次数
            List<ActivityCouponsUser> activityCouponsUsers = getByUserId(userInfo.getId(), activityId, mallMemberEquity.getId(), startDate, endDate);
            if (CollectionUtils.isEmpty(validUserCoupons)) {
                if (activityCouponsUsers.size() >= mallMemberEquityTemplate.getLimitCountPerUser()) {
                    receiveVerificationDTO.setRemainingNumberOfReceive(0);
                    receiveVerificationDTO.setReceiveStatusEnum(ReceiveStatusEnum.RESTRICTED_ACCESS);
                } else {
                    receiveVerificationDTO.setRemainingNumberOfReceive(mallMemberEquityTemplate.getLimitCountPerUser() - activityCouponsUsers.size());
                    receiveVerificationDTO.setReceiveStatusEnum(ReceiveStatusEnum.CAN_PICK);
                }
            } else {
                if (activityCouponsUsers.size() >= mallMemberEquityTemplate.getLimitCountPerUser()) {
                    receiveVerificationDTO.setRemainingNumberOfReceive(0);
                } else {
                    receiveVerificationDTO.setRemainingNumberOfReceive(mallMemberEquityTemplate.getLimitCountPerUser() - activityCouponsUsers.size());
                }
                // 超出可领取数量(已经领取了)
                receiveVerificationDTO.setReceiveStatusEnum(ReceiveStatusEnum.PICKED);
            }
            if (mallMemberEquityTemplate.getReceiveTimeRule()) {
                receiveVerificationDTO.setLastClaimTime(endDate);
                if (DateTime.now().after(endDate)) {
                    receiveVerificationDTO.setReceiveStatusEnum(ReceiveStatusEnum.ACTIVITY_HAS_ENDED);
                }
            }
            return receiveVerificationDTO;
        } else {
            if (CollectionUtils.isEmpty(validUserCoupons)) {
                receiveVerificationDTO.setReceiveStatusEnum(ReceiveStatusEnum.CAN_PICK);
                return receiveVerificationDTO;
            } else {
                // 超出可领取数量(已经领取了)
                receiveVerificationDTO.setReceiveStatusEnum(ReceiveStatusEnum.PICKED);
                return receiveVerificationDTO;
            }
        }
    }

    /**
     * 创建优惠券活动用户领取记录
     *
     * @param activityCoupons 优惠券活动
     * @param userInfo        用户
     * @return
     */
    @Override
    public void create(ActivityCoupons activityCoupons, UserInfo userInfo, UserCoupons
            userCoupons, MallMemberEquity mallMemberEquity) {
        ActivityCouponsUser activityCouponsUser = new ActivityCouponsUser();
        activityCouponsUser.setUserId(userInfo.getId());
        activityCouponsUser.setUserTel(userInfo.getUserTel());
        activityCouponsUser.setActivityCouponsId(activityCoupons.getId());
        activityCouponsUser.setUserCouponsId(userCoupons.getId());
        if (Objects.nonNull(mallMemberEquity)) {
            activityCouponsUser.setMallMemberEquityId(mallMemberEquity.getId());
        }
        activityCouponsUser.insert();
    }

    /**
     * 获取用户该活动优惠券的领取记录
     *
     * @param userId    用户ID
     * @param couponsId 优惠券活动ID
     * @return
     */
    @Override
    public List<ActivityCouponsUser> getByUserId(Long userId, Long couponsId, Long mallMemberEquityId, Date
            startTime, Date endTime) {
        return activityCouponsUserDao.getByUserIdAndActivityCouponsId(couponsId, userId, mallMemberEquityId, startTime, endTime);
    }
}
